package com.ojoin.trade.common.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.web.domain.BaseEntity;
import com.ojoin.trade.common.web.domain.Button;
import com.ojoin.trade.common.web.domain.Menu;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.service.SysManageService;
 
@Controller
@RequestMapping(value = "sys/menu")
public class MenuController extends SimpleBaseController {

	@Autowired
	private SysManageService systemService;
	
	@ModelAttribute("menu")
	public Menu get(@RequestParam(required=false) Integer id) {
		if (null!=id){
			return systemService.getMenu(id);
		}else{
			return new Menu();
		}
	}
 
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value ="list")
	public Result list() {
		List<Menu> menulist = Lists.newArrayList();
		List<Menu> sourcelist = systemService.findAllMenu();
		Menu.sortList(menulist, sourcelist, Menu.getRootId(), true);
		
		return new Result(Result.Status.OK,menulist);
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value ="mblist")
	public Result mblist() {
		List<Menu> menulist = Lists.newArrayList();
		List<Menu> sourcelist = systemService.findAllMenu();
		Menu.sortList(menulist, sourcelist, Menu.getRootId(), true);
		
		List<Button> allbuttonlist = systemService.findAllButton();
		
		if (allbuttonlist == null || allbuttonlist.size() == 0) 
			return new Result(Result.Status.OK,menulist);
		
		HashMap<Integer, List<Button>> map = new HashMap<Integer, List<Button>>();
		for(Button button : allbuttonlist) {
			if (map.get(button.getMenuId()) == null) {
				List<Button> eachlist = new ArrayList<Button>();
				eachlist.add(button);
				map.put(button.getMenuId(), eachlist);
			} else {
				map.get(button.getMenuId()).add(button);
			}
		}
		
		Set<Integer> keySet = map.keySet();
		Iterator<Integer> iterator = keySet.iterator();
		while(iterator.hasNext()) {
			Integer key = iterator.next();
			List<Button> sourcebuttonlist = map.get(key);
			Button[] beforesort_btns = sourcebuttonlist.toArray(new Button[0]);
			Arrays.sort(beforesort_btns, new Comparator<Button>() {

				@Override
				public int compare(Button o1, Button o2) {
					if (o1 == null || o2 == null || o1.getSort() == null || o2.getSort() == null)
						return 0;
					
					if (o1.getSort() < o2.getSort()) {
						return -1;
					} else if (o1.getSort() > o2.getSort()) {
						return 1;
					} else if (o1.getSort().intValue() == o2.getSort().intValue()) {
						return 0;
					}
					
					return 0;
				}
			});
			
			List<Button> aftersort_btnList = Arrays.asList(beforesort_btns);
			map.put(key, aftersort_btnList);
		}
		
		List<Object> endlist = new ArrayList<Object>();
		for(Menu menu : menulist) {
			endlist.add(menu);
			List<Button> btnlist = map.get(menu.getId());
			if (btnlist != null && btnlist.size() > 0) {
				endlist.addAll(btnlist);
			}
		}
		
        return new Result(Result.Status.OK,endlist);
	}

	@RequiresPermissions("sys:menu:view")
	@ResponseBody
	@RequestMapping(value = "form")
	public Result form(Menu menu) {
		if (menu.getParent()==null||menu.getParent().getId()==null){
			menu.setParent(new Menu(Menu.getRootId()));
		}
		menu.setParent(systemService.getMenu(menu.getParent().getId()));
		// 获取排序号，最末节点排序号+30
		if (null!=menu.getId()){
			List<Menu> list = Lists.newArrayList();
			List<Menu> sourcelist = systemService.findAllMenu();
			Menu.sortList(list, sourcelist, menu.getParentId(), false);
			if (list.size() > 0){
				menu.setSort(list.get(list.size()-1).getSort() + 10);
			}
		}
		return new Result(Result.Status.OK,menu);
	}
	
	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public Result save(Menu menu, Model model, RedirectAttributes redirectAttributes) {
		if(!systemService.getUser().isAdmin()){
			return new Result(Result.Status.ERROR, "越权操作，只有超级管理员才能添加或修改数据！");
		}
	 
		systemService.saveMenu(menu);
		return new Result(Result.Status.OK, "保存菜单'" + menu.getName() + "'成功");
	}
	
	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public Result delete(Menu menu) {
			menu.setDelFlag(BaseEntity.DEL_FLAG_DELETE);	
			systemService.deleteMenu(menu);
			return new Result(Result.Status.OK, "删除菜单成功");
	}

	@ResponseBody
	@RequestMapping(value = "btndelete")
	public Result btndelete(Button button) {
			button.setDelFlag(BaseEntity.DEL_FLAG_DELETE);	
			systemService.deleteButton(button);
			return new Result(Result.Status.OK, "删除按钮成功");
	}
	
	
	
	/**
	 * 批量修改菜单排序
	 */
	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "updateSort")
	public Result updateSort(Integer[] ids, Integer[] sorts) {
    	for (int i = 0; i < ids.length; i++) {
    		Menu menu = new Menu(ids[i]);
    		menu.setSort(sorts[i]);
    		systemService.updateMenuSort(menu);
    	}
    	return new Result(Result.Status.OK, "保存菜单排序成功!");
	}
	
	/**
	 * isShowHide是否显示隐藏菜单
	 * @param extId
	 * @param isShowHidden
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public Result treeData(@RequestParam(required=false) Integer extId,@RequestParam(required=false) String isShowHide, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Menu> list = systemService.findAllMenu();
		for (int i=0; i<list.size(); i++){
			Menu e = list.get(i);
			if (null==extId|| (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				if(isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")){
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return new Result(Result.Status.OK, mapList);
	}
}
